﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Converters;
using GroupCheer.FBGraphAPI.Core;

namespace GroupCheer.FBGraphAPI.API
{
    public class Search
    {
        public static WallPostCollection SearchPeople(string ContentKeywords)
        {
            return SearchPeople(ContentKeywords, 25);
        }

        public static WallPostCollection SearchPeople(string ContentKeyword, int SearchLimits)
        {
            string jsonResponse = Network.MakeHttpGet(
                string.Format("https://graph.facebook.com/search?q={0}&type=people&access_token={1}&limit={2}", 
                ContentKeyword, FBGraphAPIConfiguration.FBValidAccessToken, SearchLimits));
            WallPostCollection results = new WallPostCollection();
            
            JObject jsonObject = JObject.Parse(jsonResponse);

            if (jsonObject.SelectToken("data").Children().Count() > 0)
            {
                JToken dataNode = jsonObject.SelectToken("data");

                foreach (JToken token in dataNode.Children())
                {
                    WallPost post = new WallPost();
                    PropertyInfo[] properties = post.GetType().GetProperties();

                    foreach (PropertyInfo property in properties)
                    {
                        if (property.Name == "PosterID")
                            property.SetValue(post, (token.SelectToken("from").SelectToken("id") as JValue).Value, null);
                        if (property.Name == "PosterName")
                            property.SetValue(post, (token.SelectToken("from").SelectToken("name") as JValue).Value, null);
                        else
                        {
                            if (token.SelectToken(property.Name.ToLower()) != null)
                                property.SetValue(post, (token.SelectToken(property.Name.ToLower()) as JValue).Value, null);
                        }
                    }

                    results.Add(post);
                }
            }

            return results;
        }
    }
}
